package com.woniu.guoguo.controller;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.guoguo.bean.AlipayBean;
import com.woniu.guoguo.common.Result;
import com.woniu.guoguo.model.*;
import com.woniu.guoguo.service.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author： Micsal
 * @create-time： 2020.11.03 16:29
 * @version： 1.0
 * @description： 秒杀活动的信息
 */
@RestController
@Slf4j
public class AheadControllerActive {
    @Autowired
    private IRestaurantService restaurantService;
    @Autowired
    private IRestaurantImgService restaurantImgService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IMenuImgService menuImgService;
    @Autowired
    private IMenuCommentsService menuCommentsService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuCommentsImgService menuCommentsImgService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IPayService payService;
    @Autowired
    private IMenuActiveService menuActiveService;

    /**
     * 获取餐厅的所有信息(菜单信息，菜单图片，各餐厅信息，各餐厅的图片)
     *
     * @param menuId
     * @return
     */
    @GetMapping("/getMessageByRestaurantId1")
    public Result f1(int menuId, double myLnt, double myLat, HttpSession session) {
        log.info("请求菜单信息{}，{}，{}", menuId, myLnt, myLat);
        Object o=session.getAttribute("menuActive");
        if(null==o){
            return Result.fail("登录失效");
        }
        MenuActive menuActive=(MenuActive) o;
        menuId=menuActive.getMenuId();
        if (menuId <= 0) {
            return Result.fail("请求失败，非法请求ID参数");
        }
        Menu menu = menuService.getById(menuId);
        if (null == menu) {
            return Result.fail("请求失败，菜单不存在");
        }
        if (menu.getStatus() == 0) {
            return Result.fail("请求失败，菜单已下架");
        }
        //获取菜单图片
        List<String> menuImgs = menuImgService.findImagesByMenuId(menuId);
        //获取店铺列表
        List<Restaurant> restaurants1 = restaurantService.getCloseRestaurants(myLnt, myLat);
        List<Restaurant> restaurants = new ArrayList<>();
        for (Restaurant r : restaurants1) {  //去除未开业的店
            if (r.getStatus() == 01) {
                restaurants.add(r);
            }
        }
        //获取店铺的图片
        @Data
        @AllArgsConstructor
        class restImags {
            private int id;
            private List<String> imgs;
        }
        List<restImags> ms = new ArrayList<>();
        for (Restaurant r1 : restaurants) {
            if (r1.getStatus() == 1) {
                List<String> mgs = restaurantImgService.findImagesByRestId(r1.getRestaurantId());
                ms.add(new restImags(r1.getRestaurantId(), mgs));
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("restData", restaurants);
        data.put("restImgs", ms);
        data.put("menuDatas", menu);
        data.put("menuImgs", menuImgs);
        return Result.success(data);
    }

    /**
     * 分页查询评论
     *
     * @param menuId
     * @return
     */
    @GetMapping("/getCommentsByPage1")
    public Result f2(int currentPage, int pageSize, int menuId,HttpSession session) {
        log.info("评论分页查询{},{},{}", currentPage, pageSize, menuId);
        Object o=session.getAttribute("menuActive");
        if(null==o){
            return Result.fail("登录失效");
        }
        MenuActive menuActive=(MenuActive) o;
        menuId=menuActive.getMenuId();
        //评论的分页
        Page<MenuComments> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<MenuComments> ipage = menuCommentsService.findCommentsByMenuId(page, menuId);
        //获取评论的图片,用户名
        @Data
        @AllArgsConstructor
        class menuCommImgs {
            private int id;
            private String userName;
            private List<String> imgs;
        }
        List<menuCommImgs> ms = new ArrayList<>();
        for (MenuComments mc : ipage.getRecords()) {
            String un = userService.getById(mc.getUserId()).getUsername();
            List<String> mgs = menuCommentsImgService.findCommentsImgByCommentId(mc.getId());
            ms.add(new menuCommImgs(mc.getId(), un, mgs));
        }
        Map<String, Object> data = new HashMap<>();
        data.put("ipage", ipage);
        data.put("menuCommImgs", ms);
        return Result.success(data);
    }

    /**
     * 获取menuId 和 显示加评论flag
     *
     * @param menuId
     * @param session
     * @return
     */
    @GetMapping("/getMenuIdAndCommentsStatus1")
    public Result f3(int menuId, HttpSession session) {
        log.info("获取MenuId和评论与否");
        int userId = 0;
        userId=(int)session.getAttribute("userid");
        Object o=session.getAttribute("menuActive");
        if(null==o){
            return Result.fail("登录失效");
        }
        MenuActive menuActive=(MenuActive) o;
        menuId=menuActive.getMenuId();
        if (session.getAttribute("userid") != null) {
            userId = (Integer) session.getAttribute("userid");
        }
        Order order = orderService.findOrderByUserIdAndMenuId(menuId, userId);
        log.info("获取到订单状态{}", order);
        boolean bo = false;
        if (null != order && order.getState() == 1) {
            log.info("订单存入session,{}", order);
            bo = true;
            session.setAttribute("orderState2", order);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("menuId", menuId);
        data.put("addCommentsModel", bo);
//        data.put("addCommentsModel", true);
        return Result.success(data);
    }

    /**
     * 添加评论
     *
     * @return
     */
    @PostMapping(value = "/addComments1", produces = "application/json;charset=utf-8")
    public Result f4(MultipartFile[] files, double score1, double score2, double score3, String comments, HttpSession session) {
        log.info("添加评论,{},{}", files.length, comments);

        int userId = (int) session.getAttribute("userid");
        Object o=session.getAttribute("menuActive");
        if(null==o){
            return Result.fail("登录失效");
        }
        MenuActive menuActive=(MenuActive) o;
        int menuId=menuActive.getMenuId();

        Order order = (Order) session.getAttribute("orderState2");

        List<MenuCommentsImg> ms = new ArrayList<>();
//        Order order = orderService.findOrderByUserIdAndMenuId(menuId, userId);
        log.info("获取到session中的订单{}", order);
        double score = (score1 + score2 + score3) / 3;
        int orderId = order.getOrderId();
        if (files.length != 0) {
            for (MultipartFile f : files) {
                if (null != f) {
                    String fileName = UUID.randomUUID().toString() + f.getOriginalFilename();
                    String path = "/root/mine/static/comments_img/" + fileName;
                    try {
                        f.transferTo(new File(path));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
//                    File file = new File(path);
                    String url = "http://101.132.138.195:8000/comments_img/" + fileName;
                    MenuCommentsImg m1 = new MenuCommentsImg(0, menuId, url);
                    ms.add(m1);
                }
            }
        }
        MenuComments menuComments = new MenuComments(0, menuId, userId, comments, score, new Date());
        menuCommentsService.insertAMenuComment(menuComments);
        for (MenuCommentsImg m3 : ms) {
            m3.setMenuCommentsId(menuComments.getId());
        }
        orderService.updateStateTo3ById(order.getOrderId());
        menuCommentsImgService.saveBatch(ms);
        return Result.success();
    }


    /**
     * 支付请求处理
     *
     * @return
     * @throws AlipayApiException
     */
    @PostMapping(value = "/alipay1")
    public Result alipay(@RequestBody Restaurant restaurant, HttpSession session) throws AlipayApiException {
        log.info("支付请求处理:{}", restaurant);
        Object o=session.getAttribute("menuActive");
        if(null==o){
            return Result.fail("登录失效");
        }
        MenuActive menuActive=(MenuActive) o;
        int menuId=menuActive.getMenuId();
        int userId = (int) session.getAttribute("userid");

        session.setAttribute("shopShopping", restaurant);
//        int usrId = 1;
//        int menuId = 1;
        User user = userService.getById(userId);
        Menu menu = menuService.getById(menuId);
        String out_trade_no = "active"+"_"+userId + "_" + restaurant.getRestaurantId() + "_" + menuId + "_" + System.currentTimeMillis();
        String subject = menu.getType();
        double price = 0;
        price=menuActive.getActivePrice();  //获取活动价格
        price = (double) Math.round(price * 100) / 100;
        String total_amount = price + "";
        String body = menu.getMenuName();
        String s = payService.aliPay(new AlipayBean()
                .setBody(body)                      //商品描述
                .setOut_trade_no(out_trade_no)      //商户订单号
                .setTotal_amount(new StringBuffer().append(total_amount))   //付款金额
                .setSubject(subject));            //订单名称
        log.info("请求后返回的字符串:{}", s);        //是一个前端页面
        return Result.success(s);
    }


    @GetMapping("/getSearchResult1")
    public Result search(String message, String type, HttpSession session) {
        log.info("搜索的参数为：{}，{}", message, type);

        session.setAttribute("searchWord", message);

        return Result.success();
    }

}
